﻿using System;
using System.Linq;
using System.Data.Entity;
using System.Collections.Generic;

namespace MiniSched.Orm.Enumerations {
    
    public static class EnumDbSet {

        internal static void SeedOptions<TEntity, TEntityOption>(this IDbSet<TEntity> dbSet, IEnumerable<TEntityOption> options)
            where TEntity : EnumEntity<TEntityOption>, new()
            where TEntityOption : EnumEntityOption<TEntity> 
        {
            if (null == dbSet) throw new ArgumentNullException("dbSet");
            if (null == options) throw new ArgumentNullException("options");
            options.ToList().ForEach(option => dbSet.Add( new TEntity { Name = option.Name }));
        }

        public static TEntity GetOrCreate<TEntity, TEntityOption>(this IDbSet<TEntity> dbSet, TEntityOption option)
            where TEntity : EnumEntity<TEntityOption>, new()
            where TEntityOption : EnumEntityOption<TEntity>
        {
            if (null == dbSet) throw new ArgumentNullException("dbSet");
            if (null == option) throw new ArgumentNullException("option");

            var name = option.Name;
            var entity = dbSet.FirstOrDefault(e => e.Name == name);
            if (entity == null) {
                dbSet.Add(entity = new TEntity { Name = name });
            }

            return entity;
        }
    }
}
